﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FbKPI.Model;
using FbKPI.Facade;
using FbKPI.Facade.Validator;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;
using System.Web.Script.Services;
using System.Transactions;

namespace FBKPI.ProcessRequest
{
    /// <summary>
    /// Summary description for SetupYearHandler
    /// </summary>
    public class SetupYearHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string msg = this.Save();
            context.Response.Write(msg);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Save()
        {
            string msg = "OK";
            string action = HttpContext.Current.Request.QueryString["action"];
            int YearID = Convert.ToInt16(HttpContext.Current.Request.QueryString["YearID"]);
            int StartYear = 0;// Convert.ToInt16(HttpContext.Current.Request.QueryString["StartYear"]);
            int EndYear = Convert.ToInt16(HttpContext.Current.Request.QueryString["EndYear"]);
            Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(HttpContext.Current.Request.QueryString["CurrUser"]));


            SetupYearFacade sf = new SetupYearFacade();
            SetupYear SetupYear = sf.GetByID(YearID);
            SectionValidator sv = new SectionValidator();

            if (SetupYear == null)
            {
                SetupYear = new SetupYear();
                SetupYear.YearID = YearID;
                SetupYear.StartYear = StartYear;
                SetupYear.EndYear = EndYear;
                SetupYear.CreateBy = CurrUser.Email;
                //msg = sv.ValidateOnSave(sections);
            }
            else if (action != "delete")
            {
                SetupYear.StartYear = StartYear;
                SetupYear.EndYear = EndYear;
                SetupYear.LastModifiedBy = CurrUser.Email;
                //msg = sv.ValidateOnUpdate(sections);
            }
            //else if (action == "delete")
            //    sections.LastModifiedBy = CurrUser.Email;

            


            if (msg == "OK")
            {
                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    switch (action)
                    {
                        case "save":
                            msg = sf.Save(SetupYear);
                            break;
                       
                    }
                    trans.Complete();
                    trans.Dispose();
                }
            }

            return msg;
        }
    }
}